import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class UDP {

   InetAddress gr;
   DatagramPacket p;
   DatagramSocket s;
   byte[] buffer;
   int taille;
   int port;
   
   //pour client
   public UDP(String adresse, int port,int taille) throws UnknownHostException, SocketException{
	   this.taille = taille;
	   this.port = port;
	   
	   gr = InetAddress.getByName(adresse);
	   s = new DatagramSocket();
   }
   
   //pour le serveur
   public UDP(int port,int taille) throws SocketException{
	   this.port = port;
	   s = new DatagramSocket(port);
	   this.taille = taille;
	   buffer= new byte[this.taille];    
   }
   
   public void envoie(String message) throws IOException{
	   buffer= new byte[taille]; 
	   buffer = message.getBytes();
	   p = new DatagramPacket(buffer, buffer.length, gr , port);
	   //System.out.println("on envoie le msg !");
       s.send(p);
       
   }
   
   public String recevoir() throws IOException{
	   	buffer= new byte[taille]; 	
	   	p = new DatagramPacket(buffer, buffer.length);	
	   	s.receive(p);
        String r = new String(p.getData());
		return r;
		
    }
	
	public void ferme(){
	        s.close();
	}
    
  
}
